﻿using System;
using System.Windows.Forms;
using System.Drawing;

namespace OpenComposite.Forms
{
	internal partial class FormErrorWithDetails : Form
	{
		public FormErrorWithDetails()
		{
			InitializeComponent();

			this.pictureBox2.Image = SystemIcons.Error.ToBitmap();
		}

		public string Message
		{
			get { return lblMessage.Text; }
			set { lblMessage.Text = value; }
		}
		public string Details
		{
			get { return txtDetails.Text; }
			set { txtDetails.Text = value; }
		}
		public string Title
		{
			get { return this.Text; }
			set { this.Text = value; }
		}
		public bool ShowDetails
		{
			get { return grpDetails.Visible; }
			set
			{
				_showDetails = value;
				if ( grpDetails.Visible != value ) {
					grpDetails.Visible = value;
					lnkDetails.Text = txtDetails.Visible ? "Hide Details" : "Show Details";
				}
			}
		}

		private bool _showDetails;

		private void lnkDetails_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			toggleDetails();
		}

		private void toggleDetails()
		{
			this.ShowDetails = !this.ShowDetails;
		}

		private void FormErrorWithDetails_Shown(object sender, EventArgs e)
		{
			this.ShowDetails = _showDetails;
		}

	}

	public static class ErrorBox
	{
		public static DialogResult Show(string message, string details)
		{
			return Show(message, "Unhandled Exception", details, false);
		}

		public static DialogResult Show(string message, string title, string details)
		{
			return Show(message, title, details, false);
		}

		public static DialogResult Show(string message, string details, bool showDetails)
		{
			return Show(message, "Unhandled Exception", details, showDetails);
		}

		public static DialogResult Show(string message, string title, string details, bool showDetails)
		{
			DialogResult result = DialogResult.None;
			using ( FormErrorWithDetails frm = new FormErrorWithDetails() ) {
				frm.Message = message;
				frm.Title = title;
				frm.Details = details;
				frm.ShowDetails = showDetails;
				result = frm.ShowDialog();
			}
			return result;
		}

		#region Show from Exception
		public static DialogResult Show(Exception ex)
		{
			string title = string.Format("Unhandled {0}", ex.GetType().Name);
			return Show(ex.Message, title, ex.ToString());
		}

		public static DialogResult Show(Exception ex, string title)
		{
			return Show(ex.Message, title, ex.ToString(), false);
		}

		public static DialogResult Show(Exception ex, bool showDetails)
		{
			string title = string.Format("Unhandled {0}", ex.GetType().Name);
			return Show(ex.Message, title, ex.ToString(), showDetails);
		}

		public static DialogResult Show(Exception ex, string title, bool showDetails)
		{
			return Show(ex.Message, title, ex.ToString(), showDetails);
		}

		#endregion
	}
}
